<template>
  <div>
    <a-card class="box-card" shadow="nerver" title="组织" :bodyStyle="{padding:0}">
      <a-button slot="extra" type="primary" ghost icon="plus-circle" size="small" @click="formAdd">添加</a-button>
      
      <a-table v-loading="loading" :bordered="true" :pagination="false" :dataSource="dataList" @cell-click="unitNodeClick">
        <a-table-column title="名称" key="deptName" data-index="deptName"></a-table-column>
        <a-table-column title="操作" key="action" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <a-button v-if="scope.row.deptId != ancestors" size="small" type="text" icon="el-icon-edit" @click="formUpdate(scope.row)"
              v-hasPermi="['system:dept:edit']">修改</a-button>
            <a-button v-if="scope.row.deptId != ancestors" size="small" type="text" icon="el-icon-plus" @click="formAdd(scope.row)"
              v-hasPermi="['system:dept:add']">新增</a-button>
            <a-button v-if="scope.row.deptId != ancestors" size="small" type="text" icon="el-icon-delete" @click="formDelete(scope.row)"
              v-hasPermi="['system:dept:remove']">删除</a-button>
          </template>
        </a-table-column>
      </a-table>
    </a-card>

    <!-- 添加或修改部门对话框 -->
    <a-modal :title="formTitle" :visible.sync="formOpen" width="600px" append-to-body>
      <a-form ref="form" :model="form" :rules="formRules" label-width="80px">
        <a-row>
          <a-col :span="24" v-if="form.parentId !== 0">
            <a-form-item label="上级" prop="parentId">
              <VueTreeSelect v-model="form.parentId" :options="dataList" :normalizer="getUnitFormatter" :default-expand-level="3"
                placeholder="选择上级" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="名称" prop="deptName">
              <a-input v-model="form.deptName" placeholder="请输入名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="显示排序" prop="orderNum">
              <a-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="负责人" prop="leader">
              <a-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" prop="phone">
              <a-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="邮箱" prop="email">
              <a-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="关联组织" prop="dataScopeRelateArray">
              <a-select v-model="form.dataScopeRelateArray" multiple placeholder="请选择" style="width: 100%;">
                <a-option v-for="item in otherUnitOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId">
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div slot="footer" class="dialog-footer">
        <a-button type="primary" @click="formSubmit">确 定</a-button>
        <a-button @click="formCancel">取 消</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import {
    listDept,
    getDept,
    delDept,
    addDept,
    updateDept
  } from "@/api/system/dept";

  import VueTreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "UnitTree",
    components: {
      VueTreeSelect
    },
    props: {
      ancestors: {
        type: Number,
        default: 0
      },
      ancestorsOther: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        otherUnitOptions: [],
        loading: true,
        dataList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          unitId: null
        },
        form: {},
        formTitle: "",
        formOpen: false,
        // 表单校验
        formRules: {
          parentId: [{
            required: true,
            message: "上级不能为空",
            trigger: "blur"
          }],
          deptName: [{
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }],
          orderNum: [{
            required: true,
            message: "菜单顺序不能为空",
            trigger: "blur"
          }],
          email: [{
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }],
          phone: [{
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true;
        listDept({
          ancestors: this.ancestors
        }).then(response => {
          this.dataList = this.handleTree(response.data, "deptId");
          this.loading = false;
        });

        listDept({
          ancestors: this.ancestorsOther
        }).then(response => {
          let otherUnitOptions = this.handleTree(response.data, "deptId");
          this.otherUnitOptions = otherUnitOptions[0].children;
        });
      },
      /** 转换组织数据结构 */
      getUnitFormatter(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        };
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        };
      },
      // 节点单击事件
      unitNodeClick(data, col) {
        if (col.label !== '操作') {
          this.$emit('unitNodeClick', data, col);
        }
      },
      formReset() {
        this.form = {
          dataScopeRelateArray: []
        };
        this.resetForm("form");
      },
      formCancel() {
        this.formOpen = false;
        this.formReset();
      },
      formAdd(row) {
        this.formReset();
        if (row != undefined) {
          this.form.parentId = row.deptId;
        }
        this.formOpen = true;
        this.formTitle = "添加组织";
      },
      formUpdate(row) {
        this.formReset();
        const id = row.deptId;
        getDept(id).then(response => {
          let formData = response.data;
          if (formData.dataScopeRelate) {
            formData.dataScopeRelateArray = JSON.parse('[' + formData.dataScopeRelate + ']');
          }
          this.form = formData;
          this.formTitle = "修改组织";
          this.formOpen = true;
        });
      },
      /** 提交按钮操作 */
      formSubmit() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.unitId = this.form.deptId;
            this.form.unitName = this.form.deptName;
            this.form.dataScopeRelate = this.form.dataScopeRelateArray.join(',');
            if (this.form.deptId != null) {
              updateDept(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.formOpen = false;
                this.getList();
              });
            } else {
              addDept(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.formOpen = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      formDelete(row) {
        let id = row.deptId;
        this.$confirm('是否确认删除编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDept(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
      }
    }
  };
</script>
